import * as React from 'react';
import { Select, Card } from 'antd';
import { useBusinessList } from '../../hook/businessList';
import './index.less';
import { setLastSelect } from '../../common/utils';
import Chart from '../../component/chart';
import { stackBarChartTemplate, StackSeriesData } from './perfermance-stack-template';
import moment from 'moment';
import { groupData } from './utils';
import { api } from '../../common/api';
import useTimeController from '../../hook/timeController';
import dayjs from 'dayjs';
import { DateInput } from '../../component/rangeDateInput';
import { deltaMinuteIsValid } from '../static-speed/util';

const {
    useState,
    useEffect
} = React;

export default (props) => {
    const start = dayjs().add(-4, 'hour'), end = dayjs();
    const startDateController = useTimeController(start);
    const endDateController = useTimeController(end);
    const [list, projectId, setProjectId] = useBusinessList(0);
    const [selectDate, setSelectDate] = useState(moment().add(-1, 'day'));
    const [loading, setLoading] = useState(false);
    const [xAxischartData, setxAisChartData] = useState([]);
    const [seriesData, setSeriesData] = useState<StackSeriesData>(null);
    function setSelectProjectId(id) {
        setProjectId(id);
        setLastSelect(id);
    }

    const reset = () => {
        setxAisChartData([]);
        setSeriesData(null);
    }

    useEffect(() => {
        async function fetchData(id, date) {
            reset();
            if (!date) return;
            const startDate = startDateController.getTime();
            const endDate = endDateController.getTime();
            const deltaMinute = (endDate - startDate) / 1000 / 60;
            if (!deltaMinuteIsValid(deltaMinute)) {
                return;
            }
            setLoading(true);
            const result = await api({
                method: 'GET',
                url: `speed-server/${id}/performance`,
                params: {
                    startDate: startDate,
                    endDate: endDate
                }
            })
            const groupResult = groupData(result as any);
            setLoading(false);
            setxAisChartData(groupResult.createTimeData);
            const { dnsData, tcpData, sslData, ttfbData, contentData, domData, resourceData, timesData } = groupResult;
            setSeriesData({
                dnsData,
                tcpData,
                sslData,
                ttfbData,
                contentData,
                domData,
                resourceData,
                timesData
            });
        }
        if (projectId !== 0) {
            fetchData(projectId, selectDate);
        }
    }, [projectId, startDateController.getTime(), endDateController.getTime()]);

    return (
        <div className="fetch-speed">
            <span>项目选择：</span><Select
                showSearch
                value={projectId}
                onSelect={setSelectProjectId}
                filterOption={(input, option: any) =>
                    option.props.value.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                    option.props.title.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                style={{ width: 260, marginRight: 30, marginBottom: 30 }}
            >
                {
                    list.map((item) => {
                        return (
                            <Select.Option key={item.id.toString()} value={item.id} title={item.name}>
                                {item.id}.{item.name}
                            </Select.Option>
                        )
                    })
                }
            </Select>
            <h3 className="title">实时数据分析</h3>
            <div className="time-select-warpper">
                <span> 时间范围： </span>
                <DateInput controller={startDateController} time={start}></DateInput>
                <span className="gap-syboml"> ~ </span>
                <DateInput controller={endDateController} time={end}></DateInput>
            </div>
            <Card
                loading={loading}
                bordered={false}
                hoverable
                style={{
                    marginRight: 25,
                    padding: '0px 10px',
                    minHeight: 440,
                }}
            >
                <div className="chart-container">
                    <Chart styleName="stack-chart" option={stackBarChartTemplate('页面测速', seriesData, xAxischartData)}></Chart>
                </div>
            </Card>
        </div>
    );
};